import 'package:carousel_slider/carousel_slider.dart';
import 'package:cbec_app/components/base/base_image.dart';
import 'package:cbec_app/components/base/base_interactive.dart';
import 'package:cbec_app/components/base/base_page.dart';
import 'package:cbec_app/components/common/member_card_item.dart';
import 'package:cbec_app/pages/member/controller/card_member_ctr.dart';
import 'package:cbec_app/pages/member/view/usage_bottom_sheet_widget.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/AppData.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

///分类页
class MemberPage extends GetView<CardMemberController> {
  const MemberPage({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder<CardMemberController>(builder: (controller) {
      return BasePage(
        title: '会员',
        bgColor: Colors.white,
        bodyColor: Colors.white,
        children: [
          header(),
          controller.vipCardItems.isNotEmpty ? _buildCardList(controller) : const SizedBox(),
          controller.isLogin
              ? buyCardWidget(
                  '购买更多权益卡',
                  () {
                    Get.toNamed(Routes.moreVipCard);
                  },
                )
              : _buyListWidget(controller),
        ],
      );
    });
  }

  Widget _buyListWidget(CardMemberController controller) {
    return Container(
      margin: const EdgeInsets.all(20.0),
      child: Column(
        children: [
          Visibility(
            visible: controller.buyList.isNotEmpty,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text("会员套餐", style: TextStyle(fontSize: 15, fontWeight: FontWeight.w400)),
                SizedBox(
                  height: 13.w,
                ),
                SizedBox(
                  height: 170.h,
                  child: ListView.builder(
                    scrollDirection: Axis.horizontal,
                    itemCount: controller.buyList.length,
                    itemBuilder: (BuildContext context, int index) {
                      final item = controller.buyList[index];
                      return MemberCardItem(
                        type: item.type ?? 0,
                        price: item.price.toString(),
                        selected: item.isSelected ? true : false,
                        onClick: () {
                          controller.select(index);
                        },
                      );
                    },
                  ),
                ),
              ],
            ),
          ),
          if (controller.currentMainCard != null) ...[
            buyCardWidget(
              controller.currentMainCard!.receiveType == 0 ? '立即领取' : '立即购买',
              () {
                controller.buy();
              },
            ),
          ],
        ],
      ),
    );
  }

  // 卡片
  Container _buildCardList(CardMemberController controller) {
    return Container(
      color: Colors.white,
      child: Column(
        children: [
          CarouselSlider.builder(
            itemCount: controller.vipCardItems.length,
            itemBuilder: (context, index, realIndex) {
              var model = controller.vipCardItems[index];
              return Container(
                margin: const EdgeInsets.symmetric(horizontal: 5),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(10.0),
                  child: Stack(
                    children: [
                      Container(
                        color: Tools.fromHex(model.backgroundColor ?? '#FFFFFF'),
                      ),
                      Visibility(
                        visible: model.backgroundImage != null,
                        child: BaseImage(
                          url: model.backgroundImage ?? 'vip_card_defalut.png',
                          fit: BoxFit.cover,
                          width: double.infinity,
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              model.name ?? '',
                              style: TextStyle(fontSize: 16, color: Tools.fromHex('#FFFFFF')),
                            ),
                            GestureDetector(
                              onTap: () {
                                showUsageBottomSheet(context, '使用须知', model.terms ?? '');
                              },
                              child: Text(
                                '使用须知',
                                style: TextStyle(fontSize: 13, color: Tools.fromHex('#333333')),
                              ),
                            ),
                          ],
                        ),
                      ),
                      Positioned(
                        bottom: 50.h,
                        child: Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Text(
                                controller.isLogin
                                    ? '预计全年购物可平均为您节省'
                                    : controller.isLogin
                                        ? model.equity ?? ''
                                        : model.equityShipping ?? '',
                                style: TextStyle(fontSize: 14, color: Tools.fromHex('#FFFFFF')),
                              ),
                              Visibility(
                                visible: controller.isLogin,
                                child: Text(
                                  controller.infoEntity != null ? '¥${controller.infoEntity!.money.toString()}' : '',
                                  style: TextStyle(fontSize: 13, color: Tools.fromHex('#CEB681')),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                      Positioned(
                        bottom: 10.h,
                        child: Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Text(
                                model.validityDate ?? '',
                                style: TextStyle(fontSize: 12, color: Tools.fromHex('#FFFFFF')),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              );
            },
            options: CarouselOptions(
              height: 180, // 设置轮播的高度
              viewportFraction: 0.9, // 设置每个项的宽度，留出空间
              enlargeCenterPage: false, // 放大中间的图片
              // autoPlay: true, // 自动播放
              // autoPlayInterval: const Duration(milliseconds: 3000), // 自动播放间隔
              pauseAutoPlayOnTouch: true,
              onPageChanged: (index, reason) {
                controller.changeIndex(index);
              },
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // 创建一个 IndicatorWidget，只需要一个
                IndicatorWidget(
                  currentIndex: controller.currentIndex,
                  itemCount: controller.vipCardItems.length,
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 头像
  Widget header() {
    return Container(
      padding: EdgeInsets.only(top: 16.w, bottom: 16, right: 20, left: 20),
      decoration: const BoxDecoration(
        color: Colors.white,
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          SizedBox(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text("你好", style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500)),
                Text(
                  AppData.nickname ?? '',
                  style: const TextStyle(fontSize: 20, fontWeight: FontWeight.w500),
                )
              ],
            ),
          ),
          //头像
          BaseInteractive(
            onClick: () {
              // showScoreDiscountPopup();
            },
            childWidget: BaseImage(url: AppData.tokenValue == '' ? "vip_default_avatar.png" : AppData.avatar!, width: 60, height: 60, fit: BoxFit.fill, borderRadius: BorderRadius.circular(30)),
          )
        ],
      ),
    );
  }

  // 购买更多权益卡 和 立即购买 按钮样式
  Widget buyCardWidget(String title, GestureTapCallback onTap) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        margin: const EdgeInsets.symmetric(horizontal: 20, vertical: 40),
        height: 40,
        decoration: BoxDecoration(
          color: Tools.fromHex('#373739'),
          borderRadius: const BorderRadius.all(Radius.circular(20)),
        ),
        child: Center(
          child: Text(
            title ?? '',
            style: const TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w700),
          ),
        ),
      ),
    );
  }
}

class IndicatorWidget extends StatelessWidget {
  final int currentIndex; // 当前索引
  final int itemCount; // 总项数

  const IndicatorWidget({
    super.key,
    required this.currentIndex,
    required this.itemCount,
  });

  @override
  Widget build(BuildContext context) {
    return _buildLinesIndicator();
  }

  // 短线样式
  Widget _buildLinesIndicator() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: List.generate(itemCount, (index) {
        return Container(
          width: 20.0,
          height: 4.0,
          margin: const EdgeInsets.symmetric(horizontal: 4.0),
          decoration: BoxDecoration(
            color: (currentIndex == index) ? Tools.fromHex('#e35543') : Colors.grey.withOpacity(0.4),
            borderRadius: const BorderRadius.all(Radius.circular(2)),
          ),
        );
      }),
    );
  }
}
